package com.frogs.ucenter.controller;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import com.frogs.component.permission.api.service.PermissionHelper;
import com.frogs.framework.base.web.BaseController3;
import com.frogs.framework.util.DWZResponse;
import com.frogs.framework.util.PageList;
import com.frogs.framework.util.RenderUtil;
import com.frogs.framework.web.HttpRequestInfo;
import com.frogs.system.util.UserMessageTypeEnum;
import com.frogs.system.util.UserTypeEnum;
import com.frogs.ucenter.entity.UserMessageDm;
import com.frogs.ucenter.entity.UserMessageDmReceiver;
import com.frogs.ucenter.service.UserMessageDmContentService;
import com.frogs.ucenter.service.UserMessageDmReceiverService;
import com.frogs.ucenter.service.UserMessageDmService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.PropertyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
@RequestMapping("/admin/userMessageDm")
public class UserMessageDmController extends BaseController3 {
	@Resource(name = "permissionHelper")
	private PermissionHelper permissionHelper;
	
    private static final String ROOT_VIEW = "admin/userMessageDm";

    private static final String HOME_VIEW = "admin/userMessageDm/home";

    private static final String EDIT_VIEW = "admin/userMessageDm/edit";
    
    private static final String CONTENT_EDIT = "/content/edit";
    
    private static final String CONTENT_VIEW = "admin/userMessageDm/contentEdit";

    @Autowired
    private UserMessageDmService userMessageDmService;
    @Autowired
    private UserMessageDmContentService userMessageDmContentService;
    @Autowired
    private UserMessageDmReceiverService userMessageDmReceiverService;

    @RequestMapping()
    public String listUserMessageDm(HttpServletRequest request, ModelMap model) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        setRequestModelMap( request, model, true );
        getPageList( model );
        return HOME_VIEW;
    }

    @RequestMapping(EDIT)
    public String createUserMessageDm(HttpServletRequest request, ModelMap model) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        setRequestModelMap( request, model, false );
        Integer id = reqInfo.getIntParameter( "id", -1 );
        if( id > 0 ){
	   	    Map<String,Object> params = new HashMap<String,Object>();
	   	    params.put("eqDmId", id);
            PageList<UserMessageDmReceiver> receiverList = userMessageDmReceiverService.getList(params, 0, 50, false);
            StringBuffer sb = new StringBuffer();
            for (Iterator<UserMessageDmReceiver> iterator = receiverList.iterator(); iterator.hasNext();) {
            	UserMessageDmReceiver userMessageDmReceiver = (UserMessageDmReceiver) iterator.next();
				sb.append(userMessageDmReceiver.getUserId()+",");
			}
            if(sb.length()>1){
            	model.put("receiverList",sb.substring(0, sb.length()-1));
            }else{
            	model.put("receiverList","");
            }
            
            model.put( "model",userMessageDmService.getById( id ) ); 
        }
        return EDIT_VIEW;
    }

    @RequestMapping(ADD)
    public String saveUserMessageDm(HttpServletRequest request, HttpServletResponse response, ModelMap model, UserMessageDm userMessageDm) {
        setRequestModelMap(request, model, false);
        DWZResponse.Builder builder;
        try {
        	HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        	int receiverType = reqInfo.getIntParameter("receiverType");
        	userMessageDm.setSenderId(permissionHelper.getUser().getUserId().toString());
        	if(receiverType == UserMessageTypeEnum.RECEIVER_LEVEL.getId()){
            	String receiver[] = request.getParameterValues("receiver");
            	if(receiver.length<1){
            		builder = DWZResponse.getFailBuilder("新增失败：必须选择接收人" );
            	}else{
                    userMessageDmService.insert( userMessageDm ); 
            		this.addReceiver(receiver, userMessageDm.getId());
            		builder = DWZResponse.getSucessBuilder("新增成功");
            	}
        	}else{
                userMessageDmService.insert( userMessageDm ); 
                builder = DWZResponse.getSucessBuilder("新增成功");
        	}
        } catch (Exception e) {
            builder = DWZResponse.getFailBuilder("新增失败：" + e.getMessage());
        }
        RenderUtil.renderHtml(builder.build().toString(), response);
        return null;
    }

    @RequestMapping(SHOW)
    public String showUserMessageDm(HttpServletRequest request, ModelMap model) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        Integer id = reqInfo.getIntParameter( "id", -1 );
        if( id > 0 ){
            model.addAttribute( userMessageDmService.getById( id ) ); 
        }
        setRequestModelMap(request, model);
        return null;
    }

    @RequestMapping(UPDATE)
    public String updateUserMessageDm(HttpServletRequest request, HttpServletResponse response, ModelMap model, UserMessageDm userMessageDmNew) throws Exception {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        Integer id = reqInfo.getIntParameter( "id", -1 );
        if( id > 0 ){
            DWZResponse.Builder builder;
            try {
                    int receiverType = reqInfo.getIntParameter("receiverType");
                	if(receiverType == UserMessageTypeEnum.RECEIVER_LEVEL.getId()){
                    	String receiver[] = request.getParameterValues("receiver");
                    	if(receiver.length<1){
                    		builder = DWZResponse.getFailBuilder("修改失败：必须选择接收人" );
                    	}else{
                            UserMessageDm userMessageDm = userMessageDmService.getById( id ); 
                            PropertyUtils.copyProperties(userMessageDm, userMessageDmNew);
                            userMessageDm.setSenderId(permissionHelper.getUser().getUserId().toString());
                            userMessageDmService.update( userMessageDm ); 
                    		this.addReceiver(receiver, userMessageDm.getId());
                        	model.clear();
                        	builder = DWZResponse.getSucessBuilder("更新成功");
                    	}
                	}else{
                        UserMessageDm userMessageDm = userMessageDmService.getById( id ); 
                        PropertyUtils.copyProperties(userMessageDm, userMessageDmNew);
                        userMessageDm.setSenderId(permissionHelper.getUser().getUserId().toString());
                        userMessageDmService.update( userMessageDm ); 
                    	model.clear();
                    	builder = DWZResponse.getSucessBuilder("更新成功");
                	}
            } catch (Exception e) {
                builder = DWZResponse.getFailBuilder("更新失败：" + e.getMessage());
            }
            RenderUtil.renderHtml(builder.build().toString(), response);
        }
        return null;
    }

    @RequestMapping(AUDIT)
    public String auditUserMessageDm(HttpServletRequest request, HttpServletResponse response, ModelMap model, String inIdList) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        Integer status = reqInfo.getIntParameter( "status", -1 );
        
        setRequestModelMap(request, model);
        DWZResponse.Builder builder;
        try {
            String[] idArray = inIdList.split(",");
            model.put("inIdList", idArray);
            userMessageDmService.update( model ); 
            builder = DWZResponse.getSucessBuilder("删除信息成功");
        } catch (Exception e) {
            builder = DWZResponse.getFailBuilder("删除信息失败：" + e.getMessage());
        }
        RenderUtil.renderHtml(builder.build().toString(), response);
        model.clear();
        return null;
    }

    @RequestMapping(DELETE)
    public String deleteUserMessageDm(HttpServletRequest request, HttpServletResponse response, ModelMap model, @RequestParam(required=true, value="ids") String inIdList) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        setRequestModelMap(request, model);
        DWZResponse.Builder builder;
        try {
            String[] idArray = inIdList.split(",");
            model.put("inIdList", idArray);
            userMessageDmService.delete( model ); 
            builder = DWZResponse.getSucessBuilder("删除信息成功");
        } catch (Exception e) {
            builder = DWZResponse.getFailBuilder("删除信息失败：" + e.getMessage());
        }
        RenderUtil.renderHtml(builder.build().toString(), response);
        model.clear();
        return null;
    }

    private PageList<UserMessageDm> getPageList(ModelMap model) {
        PageList<UserMessageDm> userMessageDmList = userMessageDmService.getList( model, Integer.parseInt(model.get("pageNum").toString()), Integer.parseInt(model.get("numPerPage").toString()) ); 
        model.put("userMessageDmList",userMessageDmList);
        model.put("pageTurn",userMessageDmList.getPageTurn());
        return userMessageDmList;
    }
    
    @RequestMapping(CONTENT_EDIT)
    public String createUserMessageDmContent(HttpServletRequest request, ModelMap model) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        setRequestModelMap( request, model, false );
        Integer id = reqInfo.getIntParameter( "id", -1 );
        if( id > 0 ){
            model.put( "model",userMessageDmContentService.getById(id)); 
        }
        return CONTENT_VIEW;
    }
    
    private void addReceiver(String receivers[],int dmId){
   	    Map<String,Object> params = new HashMap<String,Object>();
   	    params.put("eqDmId", dmId);
    	userMessageDmReceiverService.delete(params);
    	UserMessageDmReceiver userMessageDmReceiver = null;
    	for(int i=0;i<receivers.length;i++){
    		userMessageDmReceiver = new UserMessageDmReceiver();
    		userMessageDmReceiver.setDmId(dmId);
    		userMessageDmReceiver.setReceiver(UserTypeEnum.getByType(Integer.parseInt(receivers[i])).getName());
    		userMessageDmReceiver.setUserId(receivers[i]);
    		userMessageDmReceiverService.insert(userMessageDmReceiver);
    	}
    }
}